package hivi.vn.hivigold.activities;

import hivi.vn.hivigold.R;
import hivi.vn.hivigold.database.WebService;
import hivi.vn.hivigold.objects.Item;
import hivi.vn.hivigold.utils.AccessDenied;
import hivi.vn.hivigold.utils.Formats;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class ItemActivity extends Activity {
	public static final String ITEM_KEY = "ITEM_KEY";
	public static final String NUMBER_KEY = "NUMBER_KEY";
	public static final String MONEY_KEY = "MONEY_KEY";
	public static final String ACTION_KEY = "ACTION_KEY";
	public static final String POSITION_KEY = "POSITION_KEY";
	public static final String SALEBUY_KEY = "SALEBUY_KEY";
	TextView txtNameItem;
	EditText txtTlg_da;
	EditText txtTlg_au;
	EditText txtHlg_au;
	EditText txtTien_da;
	EditText txtTien_cong;
	EditText txtTong_tlg;
	EditText txtGia_au;
	EditText txtGia_ban11;
	EditText txtSo_luong;
	EditText txtThanh_tien;

	RadioButton rboMua;
	RadioButton rboBan;
	ImageButton btnAdd;
	ImageButton btnCancel;
	ImageButton btnPrint;
	Button btnCal;
	Item item;
	int action;
	int position;
	ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.voucheritem);
		Bundle data = getIntent().getExtras();
		if (data == null) {
			finish();
		}

		item = (Item) data.getSerializable(ITEM_KEY);
		double number = data.getDouble(NUMBER_KEY);
		double money = data.getDouble(MONEY_KEY);
		action = data.getInt(ACTION_KEY);
		Log.i("action_view", action + "");
		position = data.getInt(POSITION_KEY);
		String muaban = data.getString(SALEBUY_KEY);
		txtNameItem = (TextView) findViewById(R.id.tvNameItem);
		txtTlg_da = (EditText) findViewById(R.id.txtTlg_da);
		txtTlg_au = (EditText) findViewById(R.id.txtTlg_au);
		txtHlg_au = (EditText) findViewById(R.id.txtHlg_au);
		txtTien_da = (EditText) findViewById(R.id.txtTien_da);
		txtTien_cong = (EditText) findViewById(R.id.txtTien_cong);
		txtTong_tlg = (EditText) findViewById(R.id.txtTong_tlg);
		txtGia_au = (EditText) findViewById(R.id.txtGia_au);
		txtGia_ban11 = (EditText) findViewById(R.id.txtGia_ban11);
		txtSo_luong = (EditText) findViewById(R.id.txtSo_luong);
		txtThanh_tien = (EditText) findViewById(R.id.txtThanh_tien);
		rboMua = (RadioButton) findViewById(R.id.rboBuy);
		rboBan = (RadioButton) findViewById(R.id.rboSale);
		btnAdd = (ImageButton) findViewById(R.id.btn_add);
		btnCancel = (ImageButton) findViewById(R.id.btn_cancel);
		btnCal = (Button) findViewById(R.id.btnCal);
		btnPrint = (ImageButton) findViewById(R.id.btn_print);

		txtSo_luong.setText(Formats.number(number));
		txtNameItem.setText(item.getVtName());
		txtTlg_au.setText(Formats.number(item.getTlg_au()));
		txtTlg_da.setText(Formats.number(item.getTlg_da()));
		txtTong_tlg.setText(Formats.number(item.getTong_tlg()));
		txtTien_cong.setText(Formats.money(item.getTien_cong()));
		txtTien_da.setText(Formats.money(item.getTien_da()));
		txtGia_au.setText(Formats.money(item.getGia_au()));
		txtGia_ban11.setText(Formats.money(item.getGia_ban11()));
		txtHlg_au.setText(Formats.percent(item.getHlg_au()));

		txtNameItem.setTag(item);
		txtThanh_tien.setText(Formats.money_round(money));
		if (item.getVtID().length() < 5) {
			txtSo_luong.setEnabled(false);
		}
		txtTlg_au.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (item.getVtID().length() < 5) {
					txtSo_luong.setText(s.toString());
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		if (muaban.equals("GIABAN")) {
			rboBan.setChecked(true);
			rboBan.setFocusable(true);
		} else {
			rboMua.setChecked(true);
			rboMua.setFocusable(true);
		}
		btnAdd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				hideKeyboard();
				if (checkChangeItem(item)) {
					progressDialog = new ProgressDialog(ItemActivity.this);
					progressDialog.setMessage(getResources().getString(
							R.string.alert_waiting));
					progressDialog.show();
					item.setTlg_au(Double.valueOf(txtTlg_au.getText()
							.toString().replace(",", "")));
					item.setTlg_da(Double.valueOf(txtTlg_da.getText()
							.toString().replace(",", "")));
					item.setTong_tlg(Double.valueOf(txtTong_tlg.getText()
							.toString().replace(",", "")));
					item.setTien_cong(Double.valueOf(txtTien_cong.getText()
							.toString().replace(",", "")));
					item.setTien_da(Double.valueOf(txtTien_da.getText()
							.toString().replace(",", "")));
					item.setGia_au(Double.valueOf(txtGia_au.getText()
							.toString().replace(",", "")));
					item.setGia_ban11(Double.valueOf(txtGia_ban11.getText()
							.toString().replace(",", "")));
					item.setHlg_au(Double.valueOf(txtHlg_au.getText()
							.toString().replace(",", "")));

					Message m = new Message();
					m.obj = item;
					m.what = 1;
					m.arg1 = action;
					m.arg2 = position;
					handler.sendMessage(m);
				} else {
					Double thanhtien = Double.valueOf(Math.round(((Double
							.valueOf(txtSo_luong.getText().toString()
									.replace(",", "")) * Double
							.valueOf(txtGia_ban11.getText().toString()
									.replace(",", ""))) / 1000) * 1000));
					Intent i1 = new Intent();
					Bundle bundle = new Bundle();
					bundle.putSerializable(ITEM_KEY, item);
					bundle.putString(SALEBUY_KEY,
							rboMua.isChecked() ? "MUAHANG" : "BANHANG");
					bundle.putDouble(
							NUMBER_KEY,
							Double.valueOf(txtSo_luong.getText().toString()
									.replace(",", "")));
					bundle.putDouble(MONEY_KEY, thanhtien);
					bundle.putInt(ACTION_KEY, action);
					bundle.putInt(POSITION_KEY, position);
					i1.putExtras(bundle);
					setResult(RESULT_OK, i1);

					finish();
				}
			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				hideKeyboard();
				finish();
			}
		});
		btnCal.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				hideKeyboard();
				if (checkChangeItem(item)) {
					progressDialog = new ProgressDialog(ItemActivity.this);
					progressDialog.setMessage(getResources().getString(
							R.string.alert_waiting));
					progressDialog.show();
					item.setTlg_au(Double.valueOf(txtTlg_au.getText()
							.toString().replace(",", "")));
					item.setTlg_da(Double.valueOf(txtTlg_da.getText()
							.toString().replace(",", "")));
					item.setTong_tlg(Double.valueOf(txtTong_tlg.getText()
							.toString().replace(",", "")));
					item.setTien_cong(Double.valueOf(txtTien_cong.getText()
							.toString().replace(",", "")));
					item.setTien_da(Double.valueOf(txtTien_da.getText()
							.toString().replace(",", "")));
					item.setGia_au(Double.valueOf(txtGia_au.getText()
							.toString().replace(",", "")));
					item.setGia_ban11(Double.valueOf(txtGia_ban11.getText()
							.toString().replace(",", "")));
					item.setHlg_au(Double.valueOf(txtHlg_au.getText()
							.toString().replace(",", "")));
					Message m = new Message();
					m.obj = item;
					m.what = 2;
					m.arg1 = action;
					m.arg2 = position;
					handler.sendMessage(m);
				} else {
					Double so_luong = Double.valueOf(txtSo_luong.getText()
							.toString().toString().replace(",", ""));
					txtThanh_tien.setText(Formats.money_round(so_luong
							* Double.valueOf(txtGia_ban11.getText().toString()
									.replace(",", ""))));
				}
			}
		});

		btnPrint.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!AccessDenied.KB25) {
					Toast.makeText(getBaseContext(),
							R.string.warning_access_denied, Toast.LENGTH_LONG)
							.show();
					return;
				}
				PrintItemAsync printItemAsync = new PrintItemAsync();
				printItemAsync.execute();
			}
		});
	}

	private class PrintItemAsync extends AsyncTask<String, Void, Boolean> {

		public PrintItemAsync() {
			// TODO Auto-generated constructor stub

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Toast.makeText(getBaseContext(), R.string.alert_printing_item,
					Toast.LENGTH_LONG).show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(getBaseContext(),
						R.string.alert_print_item_success, Toast.LENGTH_LONG)
						.show();
			} else {
				Toast.makeText(getBaseContext(),
						R.string.alert_print_item_fail, Toast.LENGTH_LONG)
						.show();
			}
		}

		@Override
		protected Boolean doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			return WebService.printItemInfo(getBaseContext(), item);
		}

	}

	void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getBaseContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null) {
			imm.hideSoftInputFromWindow(txtTlg_da.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtTlg_au.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtHlg_au.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtTien_da.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtTien_cong.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtTong_tlg.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtGia_au.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtGia_ban11.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtSo_luong.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(txtThanh_tien.getWindowToken(), 0);
		}

	}

	private boolean checkChangeItem(Item i) {
		double tlg_au = Double.parseDouble(txtTlg_au.getText().toString()
				.replace(",", ""));
		if (tlg_au != i.getTlg_au().doubleValue()) {
			return true;
		}
		double tlg_da = Double.parseDouble(txtTlg_da.getText().toString()
				.replace(",", ""));
		if (tlg_da != i.getTlg_da().doubleValue()) {
			return true;
		}
		double tong_tlg = Double.parseDouble(txtTong_tlg.getText().toString()
				.replace(",", ""));
		if (tong_tlg != i.getTong_tlg().doubleValue()) {
			return true;
		}
		double tien_cong = Double.parseDouble(txtTien_cong.getText().toString()
				.replace(",", ""));
		if (tien_cong != i.getTien_cong().doubleValue()) {
			return true;
		}
		double tien_da = Double.parseDouble(txtTien_da.getText().toString()
				.replace(",", ""));
		if (tien_da != i.getTien_da().doubleValue()) {
			return true;
		}
		double gia_au = Double.parseDouble(txtGia_au.getText().toString()
				.replace(",", ""));
		if (gia_au != i.getGia_au().doubleValue()) {
			return true;
		}
		double gia_ban = Double.parseDouble(txtGia_ban11.getText().toString()
				.replace(",", ""));
		if (gia_ban != i.getGia_ban11().doubleValue()) {
			return true;
		}
		double hlg_au = Double.parseDouble(txtHlg_au.getText().toString()
				.replace(",", ""));
		if (hlg_au != i.getHlg_au().doubleValue()) {
			return true;
		}
		return false;
	}

	Handler handler = new Handler(new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Item i = (Item) msg.obj;
			Double giaban = WebService.calPrice(ItemActivity.this, i,
					rboBan.isChecked() ? "GIABAN" : "GIAMUA");
			txtGia_ban11.setText(Formats.money(giaban));
			i.setGia_ban11(giaban);
			Double so_luong = Double.valueOf(txtSo_luong.getText().toString());

			txtThanh_tien.setText(Formats.money_round(so_luong * giaban));
			txtNameItem.setTag(i);
			progressDialog.dismiss();
			if (msg.what == 1) {
				Intent i1 = new Intent();
				Bundle bundle = new Bundle();
				bundle.putSerializable(ITEM_KEY, i);
				bundle.putString(SALEBUY_KEY, rboMua.isChecked() ? "MUAHANG"
						: "BANHANG");
				bundle.putDouble(
						NUMBER_KEY,
						Double.valueOf(txtSo_luong.getText().toString()
								.replace(",", "")));
				bundle.putDouble(
						MONEY_KEY,
						Double.valueOf(txtThanh_tien.getText().toString()
								.replace(",", "")));
				bundle.putInt(ACTION_KEY, action);
				bundle.putInt(POSITION_KEY, position);
				i1.putExtras(bundle);
				setResult(RESULT_OK, i1);
				Log.i("action_view", action + " return");
				finish();
			}
			return false;
		}
	});

	public static void onStartIntent(Activity c, Item item, double number,
			double money, String buysale, int action, int position) {
		Intent i = new Intent(c, ItemActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable(ITEM_KEY, item);
		bundle.putDouble(NUMBER_KEY, number);
		bundle.putDouble(MONEY_KEY, money);
		bundle.putInt(ACTION_KEY, action);
		bundle.putInt(POSITION_KEY, position);
		bundle.putString(SALEBUY_KEY, buysale);
		i.putExtras(bundle);
		c.startActivityForResult(i, VoucherActivity.ITEM_REQUEST);
	}
}
